#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/7/31 16:50
# @Author  : youfeng
import os
import random
import threading
import time


class ProxyFetcher(object):
    def __init__(self, config_path, log=None):
        self.log = log
        self.config_path = config_path

        # 初始化代理
        self.visit_list = self.__get_list_from_config()
        self.visit_list_text = "\n".join(self.visit_list)
        self.proxy_length = len(self.visit_list)
        if self.proxy_length > 0:
            self.__point = random.randint(0, self.proxy_length - 1)
        else:
            self.__point = 0

        # 启动定时更新线程
        self.__update_thread = threading.Thread(target=self.__update, )
        self.__update_thread.setDaemon(True)
        self.__update_thread.start()

    @staticmethod
    def __process(ip):
        # proxy = "http://hz201807:hz201807@118.89.231.218:7777"
        proxy = "http://" + ip
        return proxy

    def __get_list_from_config(self):
        proxy_list = []
        if not os.path.exists(self.config_path):
            self.log.error("配置文件不存在: {}".format(self.config_path))
            return proxy_list

        with open(self.config_path) as p_file:
            for line in p_file:
                ip = line.strip().strip("\n").strip("\r")

                proxy = self.__process(ip)
                proxy_list.append(proxy)

        return sorted(proxy_list)

    def __update(self):
        while True:

            try:

                # 获得静态代理
                visit_list = self.__get_list_from_config()

                # 需要先判断获取的代理数目是否大于0
                if len(visit_list) > 0:
                    # 比较是否发生变动
                    if cmp(visit_list, self.visit_list) != 0:
                        self.proxy_length = len(visit_list)
                        self.visit_list = visit_list
                        self.visit_list_text = "\n".join(self.visit_list)
                        self.log.info("IP发生变动，需要进行切换...")
            except Exception as e:
                self.log.error("更新代理异常: ")
                self.log.exception(e)

            time.sleep(60)

    # 获得代理
    def get_proxy(self):
        self.__point += 1
        if self.__point >= self.proxy_length:
            self.__point = 0

        if self.proxy_length > 0 and self.__point < self.proxy_length:
            return self.visit_list[self.__point]

        return ""

    # 批量获得代理
    def get_proxy_list(self):
        return self.visit_list

    # 批量获得代理
    def get_proxy_list_text(self):
        return self.visit_list_text

    # 获得代理数目
    def get_proxy_num(self):
        return self.proxy_length

# if __name__ == '__main__':
#     from logger import AppLogger
#
#     log = AppLogger('static_proxy_server.log').get_logger()
#     fetcher = ProxyFetcher("proxies.txt", log)
#     while True:
#         log.info("休眠...")
#         time.sleep(10)
